package com.tanhua.app.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.sun.org.apache.regexp.internal.RE;
import com.tanhua.api.db.QuestionApi;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.RecommendUserApi;
import com.tanhua.api.mongo.VisitorsApi;
import com.tanhua.app.interceptor.UserHolder;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.mongo.Visitors;
import com.tanhua.domain.vo.PageBeanVo;
import com.tanhua.domain.vo.RecommendUserVo;
import com.tanhua.domain.vo.VisitorsVo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MakeFriendService {
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    public RecommendUserApi recommendUserApi;
    @Autowired
    public StringRedisTemplate stringRedisTemplate;
    @Reference
    public VisitorsApi visitorsApi;
    @Reference
    public QuestionApi questionApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    public ResponseEntity findTodayBest() {
        //根据当前用户id查询推荐用户最高的信息
        RecommendUser recommendUser = recommendUserApi.findMaxScore(UserHolder.getUserId());
        if (recommendUser == null) {
            //新用户  默认数据
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1L);
            recommendUser.setScore(99D);

        }

        // 封装vo 对象
        RecommendUserVo vo = new RecommendUserVo();
        //获得推荐用户详情
        UserInfo userInfo = userInfoApi.fingByUserId(recommendUser.getUserId());
        vo.setUserInfo(userInfo);
        // 缘分值
        vo.setFateValue(recommendUser.getScore().longValue());


        //返回vo
        return ResponseEntity.ok(vo);
    }
             //推荐列表

    public ResponseEntity recommendation(Integer pageNum, Integer pageSize) {
        // 调用api 查询推荐列表
        PageBeanVo pageBeanVo = recommendUserApi.findByPage(pageNum, pageSize, UserHolder.getUserId());
        //封装Recommenduservo
        List<RecommendUserVo> voList = new ArrayList<>();
        List<RecommendUser> recommendUserList = (List<RecommendUser>) pageBeanVo.getItems();
        if (CollectionUtil.isEmpty(recommendUserList)) {
            //新用户  构造默认数据
            recommendUserList = defaultRecommendUserList();
        }
        for (RecommendUser recommendUser : recommendUserList) {
            RecommendUserVo vo = new RecommendUserVo();
            // 查询推荐用户详情
            UserInfo userInfo = userInfoApi.fingByUserId(recommendUser.getUserId());
            vo.setUserInfo(userInfo);
            // 缘分值
            vo.setFateValue(recommendUser.getScore().longValue());
            //添加到集合
            voList.add(vo);

        }
        pageBeanVo.setItems(voList);
        return ResponseEntity.ok(pageBeanVo);


    }


       // 构造推荐用户的默认数据
    private List<RecommendUser> defaultRecommendUserList() {
        List<RecommendUser> list = new ArrayList<>();

        Long[] userIdArray = new Long[]{2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L};

        for (Long userId : userIdArray) {
            RecommendUser recommendUser = new RecommendUser();
            recommendUser.setUserId(userId);
            recommendUser.setScore(RandomUtil.randomDouble(66, 98));
            list.add(recommendUser);


        }
        return list;
    }
        // 访客
        public ResponseEntity visitors() {
            // 1、获取上次访问时间
            String historyDate = stringRedisTemplate.opsForValue().get("visitors_user_" + UserHolder.getUserId());

            List<VisitorsVo> voList = new ArrayList<>();
            if (StrUtil.isNotEmpty(historyDate)) {
                // 2、老用户，调用api查询历史访客
                List<Visitors> visitorsList = visitorsApi.topVisitors(UserHolder.getUserId(), Long.valueOf(historyDate));
                if (CollectionUtil.isNotEmpty(visitorsList)) {
                    for (Visitors visitors : visitorsList) {
                        // 3、封装访客vo
                        VisitorsVo vo = new VisitorsVo();
                        UserInfo userInfo = userInfoApi.fingByUserId(visitors.getVisitorUserId());
                        // 用户信息
                        vo.setUserInfo(userInfo);
                        // 缘分值
                        vo.setFateValue(visitors.getScore().longValue());

                        voList.add(vo);
                    }
                }
            }

            // 4、记录本次访问时间
            stringRedisTemplate.opsForValue().set("visitors_user_" + UserHolder.getUserId(), System.currentTimeMillis() + "");

            // 5、返回vo集合
            return ResponseEntity.ok(voList);
        }

    public ResponseEntity personalInfo(Long bestUserId) {
        //先查询用户详情
        UserInfo userInfo=userInfoApi.fingByUserId(bestUserId);
        // 查询用户的缘分值
        Long score=recommendUserApi.findbestUserScore(bestUserId,UserHolder.getUserId());

        //封装vo
        RecommendUserVo vo =new RecommendUserVo();
        vo.setUserInfo(userInfo);
        vo.setFateValue(score);
         //返回vo
        return ResponseEntity.ok(vo);
    }

    public String findQuestionsByUserId(Long userId) {
        Question question =questionApi.findByUserId(userId);
        if (question == null) {
            return "闫德福是我大哥 崩你啊!!! 你等回寝的!!!";
        }
        return question.getStrangerQuestion();
    }



    public ResponseEntity replyQuestions(String userId, String reply) {
        Map<String, String> msg = new HashMap<>();
        msg.put("userId", UserHolder.getUserId().toString()); // 登录人用户id
        UserInfo userInfo = userInfoApi.fingByUserId(UserHolder.getUserId());
        msg.put("nickname", userInfo.getNickname()); // 登录人用户昵称
        String questions = findQuestionsByUserId(Long.valueOf(userId));
        msg.put("strangerQuestion", questions); // 佳人的陌生人问题
        msg.put("reply", reply) ; // 登录人回答的问题

        String json = JSON.toJSONString(msg);
        huanXinTemplate.sendMsg(userId,json); // 通过环信，向指定用户发送消息

        return ResponseEntity.ok(null);
    }
    }
